package com.lam.common.components.easyexcel.imp.model;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.lam.common.components.easyexcel.handlers.AutoColumnWriteHandler;
import com.lam.common.config.AppBaseConfig;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.JsonUtil;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;

/**
 * @author lam
 *
 * @param <Ie> 用于接收数据对象的Java类
 * @param <R> 用于保存数据对象的Java类
 */
public class ImportResultHandler<Ie, R> {
	
	private String fileName;
	private String filePath;
	private ExcelWriter excelWriter;
	private WriteSheet writeSheet;
	private Class<Ie> clazz;
	private List<List<String>> head;
	private List<String> headPropList;
	
	public ImportResultHandler(String fileName, Class<Ie> clazz) {
		this.fileName = fileName;
		this.filePath = AppBaseConfig.me().getDownloadTmpPath() + fileName;
		this.clazz = clazz;
		parseHead();
		excelWriter = EasyExcel.write(this.filePath).head(head).registerWriteHandler(new AutoColumnWriteHandler()).build();
		writeSheet = EasyExcel.writerSheet("导入结果").build();
	}
	
	public void write(List<ImportEntry<Ie, R>> list) {
		excelWriter.write(parseData(list), writeSheet);
	}
	
	private List<List<Object>> parseData(List<ImportEntry<Ie, R>> list){
		List<List<Object>> dataList = new ArrayList<>();
		for (ImportEntry<Ie, R> wrapper : list) {
			List<Object> rowData = new ArrayList<>();
			Map<String, Object> json = JsonUtil.parseJSON(wrapper.getOrigObject());
			for (String prop : headPropList) {
				rowData.add(json.get(prop));
			}
			rowData.add(wrapper.getImportResult());
			dataList.add(rowData);
		}
		return dataList;
	}
	
	private void parseHead() {
		List<String> headPropList = new ArrayList<>();
		List<List<String>> head = new ArrayList<>();
		List<Field> fieldList = BeanUtil.getBusinessFields(this.clazz);
		for (Field field : fieldList) {
			int mdf = field.getModifiers();
			// 默认,public,private,protected
			if (mdf == 0 || mdf == 1 || mdf == 2 || mdf == 4) {
				ExcelProperty a = field.getAnnotation(ExcelProperty.class);
				if (a != null) {
					headPropList.add(field.getName());
					head.add(Arrays.asList(a.value()));
				}
			}
		}
		head.add(Collections.singletonList("错误描述"));
		this.head = head;
		this.headPropList = headPropList;
	}
	
	public void close() {
		// 千万别忘记close 会帮忙关闭流
        if (excelWriter != null) {
        	excelWriter.finish();
        }
	}

	public String getFilePath() {
		return filePath;
	}

	public ExcelWriter getExcelWriter() {
		return excelWriter;
	}

	public WriteSheet getWriteSheet() {
		return writeSheet;
	}

	public Class<Ie> getClazz() {
		return clazz;
	}

	public List<String> getHeadPropList() {
		return headPropList;
	}

	public String getFileName() {
		return fileName;
	}

}
